from flask import Flask
import click
from .models import db


def create_app(**kwargs):
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)
    register_celery(celery=kwargs.get('celery'), app=app)
    register_blueprints(app)
    register_commands(app)
    return app


def register_celery(celery, app):
    class ContextTask(celery.Task):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask


def register_blueprints(app):
    from .views import th
    app.register_blueprint(th, url_prefix='/')


def register_commands(app):
    @app.cli.command()
    @click.option('--drop', is_flag=True, help='Create after drop.')
    def initdb(drop):
        """Init databases."""
        if drop:
            click.confirm(
                'This operation will delete the database, do you want to continue?',
                abort=True)
            db.drop_all()
            click.echo('Drop tables.')
        db.create_all()
        click.echo('Initialized database.')
